/**
 * @FileName: LocationFragment.java
 * @Package:com.bdtop.dbl.ui.fragments
 * @Description: TODO
 * @author: MingjunLi
 * @date:2014-9-26
 * @version V1.0
 */

package com.bdtop.dbl.ui.activities.fragments;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Geocoder;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapLoadedCallback;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.InfoWindow.OnInfoWindowClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.bdtop.dbl.BaseActivity;
import com.bdtop.dbl.BaseFragment;
import com.bdtop.dbl.DBLApplication;
import com.bdtop.dbl.R;
import com.bdtop.dbl.model.DeviceInfo;
import com.bdtop.dbl.server.ServerApiFactory;
import com.bdtop.dbl.server.response.BaseResponse;
import com.bdtop.dbl.server.response.GetImgResponse;
import com.bdtop.dbl.server.response.PositionResponse;
import com.bdtop.dbl.thirdparty.asynchttp.RequestCallback;
import com.bdtop.dbl.thirdparty.map.OfflineMapDownActivity;
import com.bdtop.dbl.ui.activities.device.DeviceAddTipActivity;
import com.bdtop.dbl.ui.activities.main.MainActivity;
import com.bdtop.dbl.ui.view.TipsView;
import com.bdtop.dbl.utils.AnimUtils;
import com.bdtop.dbl.utils.Constants;
import com.bdtop.dbl.utils.DBLDebug;
import com.bdtop.dbl.utils.HttpClient;
import com.bdtop.dbl.utils.ImageUtils;
import com.bdtop.dbl.utils.NetworkUtils;
import com.bdtop.dbl.utils.Preferences;
import com.igexin.sdk.PushConsts;

/**
 * @ClassName: LocationFragment
 * @Description: TODO
 * @author: MingjunLi
 * @date:2014-9-26
 */
public class LocationFragment extends BaseFragment {

	public Animation slideInRight, fadeOut;
	public View layoutMode, layoutLocation, layoutTrack, layoutDeviceList, layoutMapDown;
	private TextView txMode, txLocation;
	private ImageView imgMode;
	// private View popFlagLine;

	private MapView mMapView;
	private BaiduMap mBaiduMap;
	private Marker mSelfMarker, mDeviceMarker;
	private Overlay circleOverlay;
	
	private TipsView viewTips;

	String[] lMode;

	// 数据加载
	public void init() {
		// 没有绑定任何设备
		if (DBLApplication.getInstance().deviceInfoList == null || DBLApplication.getInstance().deviceInfoList.size() < 1) {
			// 隐藏轨迹查询按钮
			if(holder != null){
				((MainActivity) holder).btnTrack.setVisibility(View.GONE);	
			
				// 显示消息
				setAndShowWaitingMessage(R.string.no_device_bind);
				// 如果用户没有设备，为提示信息添加点击跳转至增加设备的页面
				BaseActivity main = (BaseActivity) holder;
				TextView wait = main.getWaitingText();
				wait.setOnClickListener(toAddDeviceListener);	

				// 隐藏列表按钮
				if (layoutDeviceList.getVisibility() != View.GONE) {
					layoutDeviceList.startAnimation(fadeOut);
					layoutDeviceList.setVisibility(View.GONE);
				}
				// 隐藏追随按钮
				if (layoutTrack.getVisibility() != View.GONE) {
					layoutTrack.startAnimation(fadeOut);
					layoutTrack.setVisibility(View.GONE);
				}
			
			}
		} else {
			if( holder != null){
				// 有绑定设备
				if (!isHidden ) {
					((MainActivity) holder).btnTrack.setVisibility(View.VISIBLE);
				}
				// 重设等待文本点击监听
				BaseActivity main = (BaseActivity) holder;
				TextView wait = main.getWaitingText();
				wait.setOnClickListener(main.onWaitClickListenter);
	
				// 如果当前默认选中设备为空，则设置为列表中第一个 [ 先设置 当前设备为上次退出时候选中设备]
				if (DBLApplication.getInstance().currentDi == null &&  DBLApplication.getInstance().deviceInfoList != null) {
					String lastMdn = Preferences.getLastSelectedDevice();
					if (!TextUtils.isEmpty(lastMdn)) {
						boolean find = false;
						for (DeviceInfo di : DBLApplication.getInstance().deviceInfoList) {
							if (lastMdn.equals(di.mdn)) {
								find = true;
								DBLApplication.getInstance().currentDi = di;
								break;
							}
						}
						if (!find) {
							DBLApplication.getInstance().currentDi = DBLApplication.getInstance().deviceInfoList.get(0);
						}
					} else {
						DBLApplication.getInstance().currentDi = DBLApplication.getInstance().deviceInfoList.get(0);
					}
				}
				// 如果只有一个绑定设备，隐藏列表按钮
				if (DBLApplication.getInstance().deviceInfoList.size() == 1) {
					if (layoutDeviceList.getVisibility() != View.GONE) {
						layoutDeviceList.startAnimation(fadeOut);
						layoutDeviceList.setVisibility(View.GONE);
					}
				} else {
					// 如果有多个设备，显示列表按钮
					if (layoutDeviceList.getVisibility() != View.VISIBLE) {
						layoutDeviceList.setVisibility(View.VISIBLE);
						layoutDeviceList.startAnimation(slideInRight);
					}
				}
				// 显示追随按钮
				if (layoutTrack.getVisibility() != View.VISIBLE) {
					layoutTrack.setVisibility(View.VISIBLE);
					layoutTrack.startAnimation(slideInRight);
				}
				// 重新设置模式按钮显示内容
				resetDeviceModeView();
	
				// 将当前选中设备画在地图上
				drawDeviceInfoOnTheMap(DBLApplication.getInstance().currentDi);
			
			}
		}
		
		// add 开启应用 自追随一次
		if(firstTrack){
			firstTrack = false; 
			if(DBLApplication.getInstance().deviceInfoList != null){
				requestGetPosition();
			}
		}
	}
	
	private boolean firstTrack = true;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_location, container, false);
		initViews(view);

		lMode = getResources().getStringArray(R.array.device_location_mode_short);

		slideInRight = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_in_right);
		fadeOut = AnimationUtils.loadAnimation(getActivity(), R.anim.fade_out);

		layoutDeviceList.startAnimation(slideInRight);
		layoutLocation.startAnimation(slideInRight);

		MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.zoomTo(Constants.DEFAULT_ZOOM_LEVEL);
		mBaiduMap.animateMapStatus(mapStatusUpdate);

		String[] lat_lng = Preferences.getLastSelfLocation(holder);
		if (lat_lng != null) {
			LatLng point = new LatLng(Double.parseDouble(lat_lng[0]), Double.parseDouble(lat_lng[1]));
//			drawSelfInfoOnTheMap(point);
		}
		
		viewTips = (TipsView) view.findViewById(R.id.view_tips);

		// fix 10 秒后获得数据
		fixGetAllDeviceInfoAtCreateTime();
		
		registerPushReceiver();
		
		return view;
	}

	private int fixTime = 2;

	private void fixGetAllDeviceInfoAtCreateTime() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				try {
					if (DBLApplication.getInstance().deviceInfoList == null) {
						requestAllDeviceInfo();
						fixTime--;
						if (fixTime > 0) {
							fixGetAllDeviceInfoAtCreateTime();
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, 1000);

	}

	private OnClickListener mClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {

			switch (v.getId()) {
			case R.id.layout_location:
				// 点击自己，启动百度定位查找自己经纬度
				searchMyLocation();
				break;
			case R.id.layout_tracking:
				// 点击追随，请求当前默认设备最新位置
				viewTips.startAnim();  // 手动点击时候，显示tips
				requestGetPosition();
				break;
			case R.id.layout_device_list:
				// 点击列表
				if (DBLApplication.getInstance().deviceInfoList == null || DBLApplication.getInstance().deviceInfoList.size() < 1) {
					// 如果列表内容为空，重新发起获得所有设备信息即时数据请求
					requestAllDeviceInfo();
				} else {
					// 如果列表有内容，显示选择当前默认设备对话框
					showDeviceListDialog();
				}
				break;
			case R.id.layout_mode:
				// 点击模式，显示选择修改当前模式对话框
				showModiLocationModeDialog();
				break;
			case R.id.layout_map_down:
				// 点击下载，显示下载离线地图对话框
				showToDownMapDialog();
				break;
			}
		}
	};

	/** 查找当前默认设备的最新Position信息 */
	private void requestGetPosition() {
		if (!isHidden) {
			setAndShowWaitingMessage(R.string.wating_position);
		}
		final String mdn = DBLApplication.getInstance().currentDi.mdn;
		ServerApiFactory.getApiImpl().getPosition(loginSign, mdn, new RequestCallback() {
			@Override
			public void onSuccess(String rawData, Object response) {
				clearAndHiddenWaitingMessage();
				PositionResponse pr = (PositionResponse) response;
				if (pr.getStatus().equals(Constants.REQUEST_SUCCESS)) {
					// 成功，更新数据 并且在地图上重绘点
					DBLApplication.getInstance().currentDi.pos = pr.getPos();
					drawDeviceInfoOnTheMap(DBLApplication.getInstance().currentDi);
				} else {
					if (!isHidden) {
						setAndShowWaitingMessage(pr.getDesc());
					}
					if(viewTips != null){
						viewTips.stopAnim();
					}
				}
			}

			@Override
			public void onError(int statusCode, Throwable e, String rawData) {
				clearAndHiddenWaitingMessage();
				if (NetworkUtils.isNetConnect(holder)) {
					showToast(R.string.oper_error);
				} else {
					showToast(R.string.net_error);
				}
			}
		});
	}
	
	private void initViews(View view) {
		// 初始化搜索模块，注册事件监听

		mMapView = (MapView) view.findViewById(R.id.bmap_view);
		hideBaiDuZoomController(mMapView);
		mBaiduMap = mMapView.getMap();

		layoutLocation = view.findViewById(R.id.layout_location);
		layoutMode = view.findViewById(R.id.layout_mode);
		layoutMode.setVisibility(View.GONE);
		layoutTrack = view.findViewById(R.id.layout_tracking);
		layoutMode.setVisibility(View.GONE);
		layoutDeviceList = view.findViewById(R.id.layout_device_list);
		txMode = (TextView) view.findViewById(R.id.tx_mode);
		imgMode = (ImageView) view.findViewById(R.id.img_mode);
		txLocation = (TextView) view.findViewById(R.id.tx_location);
		layoutMapDown = view.findViewById(R.id.layout_map_down);

		layoutLocation.setOnClickListener(mClickListener);
		layoutTrack.setOnClickListener(mClickListener);
		layoutDeviceList.setOnClickListener(mClickListener);
		// layoutDeviceList.setEnabled(false);
		layoutMode.setOnClickListener(mClickListener);
		layoutMapDown.setOnClickListener(mClickListener);
		layoutMapDown.setVisibility(View.GONE);

		layoutMode.setVisibility(View.INVISIBLE);
		layoutTrack.setVisibility(View.GONE);
		// popFlagLine = view.findViewById(R.id.pop_flag_line);

		txMapLoad = view.findViewById(R.id.tx_map_load);
		mBaiduMap.setOnMapLoadedCallback(onMapLoadedCallback);
	}

	private View txMapLoad;
	private OnMapLoadedCallback onMapLoadedCallback = new OnMapLoadedCallback() {
		/** 地图加载完成回调函数 */
		public void onMapLoaded() {
			txMapLoad.postDelayed(new Runnable() {
				@Override
				public void run() {
					txMapLoad.startAnimation(AnimUtils.cearteAlpha(1f, 0f));
					txMapLoad.setVisibility(View.GONE);
				}
			}, 1000);
		
		}
	};

	/**
	 * 将自己信息画在地图上
	 * 
	 * @param point
	 *            要画的点
	 * @param iconId
	 *            作为显示的图标
	 */
	private void drawSelfInfoOnTheMap(LatLng point) {
		if (mSelfMarker != null) {
			mSelfMarker.remove();
		}
		// 加载作为显示自己信息图层的视图
		View view = LayoutInflater.from(holder).inflate(R.layout.infowindow_latlng_point_info, null);

		String selfLocation = getString(R.string.self_location);
		String city = getString(R.string.city);
		String address = Preferences.getLocationInfo(holder);

		// 获取自身位置信息
		String value = selfLocation;
		try {
			value += "\n" + address.substring(address.indexOf(city) + 1);
		} catch (Exception e) {
		}
		((TextView) view.findViewById(R.id.tx_point_info)).setText(value);
		// 将视图放入百度图层
		InfoWindow mInfoWindow = new InfoWindow(view, point,0);
		
//		BitmapDescriptor d = BitmapDescriptorFactory.fromView(view);
//		InfoWindow mInfoWindow = new InfoWindow( d, point, 0,
//				null);
		
		// 显示在地图上
		mBaiduMap.showInfoWindow(mInfoWindow);

		MarkerOptions mSelfMarkerOptions = new MarkerOptions();
		mSelfMarkerOptions.icon(bdSelf);
		mSelfMarkerOptions.position(point);

		// 将自身点显示在地图上
		mSelfMarker = (Marker) mBaiduMap.addOverlay(mSelfMarkerOptions);


		// 动画移动至当前设置点（经纬度）
		MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLng(point);
		mBaiduMap.animateMapStatus(mapStatusUpdate);
	}

	/**
	 * 将设备信息画在地图上
	 * 
	 * @param dInfo
	 *            设备信息
	 */
	private void drawDeviceInfoOnTheMap(final DeviceInfo dInfo) {
		try {
			// 如果pos点信息为空，不做事
			if (dInfo.pos == null) {
				return;
			}
			// 移除上一个设备点在地图上
			if (mDeviceMarker != null) {
				mDeviceMarker.remove();
			}
			// 移除上一个设备点的半透圆圈
			if (circleOverlay != null) {
				circleOverlay.remove();
			}

			final LatLng point = new LatLng(dInfo.pos.getLat(), dInfo.pos.getLon());
			// 加载作为显示设备信息图层的视图
			final View view = LayoutInflater.from(holder).inflate(R.layout.infowindow_device_info, null);
			MarkerOptions mDeviceMarkerOptions = new MarkerOptions();
			mDeviceMarkerOptions.position(point);
			mDeviceMarkerOptions.icon(bdDevice);
			// 将设备点显示在地图上
			mDeviceMarker = (Marker) mBaiduMap.addOverlay(mDeviceMarkerOptions);
			// 将设备点的半透圆圈显示在地图上 [基站定位]
			if (dInfo.av == 1) {
				int strokeColor = Color.parseColor("#07638D");
				int fillColor = Color.parseColor("#99C2E2EF");
				OverlayOptions circleOptions = new CircleOptions().center(point).fillColor(fillColor).stroke(new Stroke(2, strokeColor))
						.radius(500);
				circleOverlay = mBaiduMap.addOverlay(circleOptions);
				circleOverlay.setZIndex(40); // 圈放最下面
			}

			mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {
				@Override
				public boolean onMarkerClick(Marker arg0) {
					// 在地图上点击设备点，是点击的设备切换为当前默认设备
					if (DBLApplication.getInstance().deviceInfoList != null) {
						for (DeviceInfo di : DBLApplication.getInstance().deviceInfoList) {
							if (di.mdn.equals(dInfo.mdn)) {
								DBLApplication.getInstance().currentDi = di;
								break;
							}
						}
						// 将设备信息画在地图上
						drawDeviceInfoOnTheMap(DBLApplication.getInstance().currentDi);
					}
					return true;
				}
			});

			// 加载设备头像视图
			ImageView imgDeviceHead = (ImageView) view.findViewById(R.id.img_device_head);
			// 设置当前设备的头像
			setDeviceHeadImg(imgDeviceHead);

			String pMsg = dInfo.name;
			((TextView) view.findViewById(R.id.tx_device_location)).setText(pMsg);
			// 将设备信息视图放入百度图层
			
			BitmapDescriptor d = BitmapDescriptorFactory.fromView(view);
			InfoWindow mInfoWindow = new InfoWindow( d, point, 0,
					new OnInfoWindowClickListener() {
						@Override
						public void onInfoWindowClick() {
							((MainActivity) holder).showDeviceInfoPop();
						}
					});
			// 显示图层在地图上
			mBaiduMap.showInfoWindow(mInfoWindow);
			// 动画移动至当前设置点
			MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLng(point);
			mBaiduMap.animateMapStatus(mapStatusUpdate);
		} catch (Exception e) {
			DBLDebug.loge("LocationFragment drawDeviceInfoOnTheMap - map exception?\n" + e.getMessage());
		}
	}

	private BitmapDescriptor bdDevice = BitmapDescriptorFactory.fromResource(R.drawable.location3);
	private BitmapDescriptor bdSelf = BitmapDescriptorFactory.fromResource(R.drawable.location);
	
	private boolean isSearchMyLocation = false;

	/**
	 * 启动百度定位查找自己经纬度 正在定位是点击停止定位
	 */
	private void searchMyLocation() {
		isSearchMyLocation = !isSearchMyLocation;
		if (isSearchMyLocation) {
			DBLApplication.getInstance().startLocationClient(mMyLocationListener);
			txLocation.setText(R.string.wait);
			if (!isHidden) {
				setAndShowWaitingMessage(R.string.wating_selflocation);
			}
		} else {
			DBLApplication.getInstance().stopLocationClient(mMyLocationListener);
			txLocation.setText(R.string.mlocation_btn_short);
			clearAndHiddenWaitingMessage();
		}
	}

	/**
	 * 自身经纬度定位回调
	 */
	private BDLocationListener mMyLocationListener = new BDLocationListener() {
		@Override
		public void onReceiveLocation(BDLocation location) {
			layoutLocation.performClick(); // to stop the scan self location
			// mBaiduMap.clear();
			DBLDebug.logi("self location has receive");
			if (location.getCityCode() == null) {
				showToast("定位失败");
				return;
			}

			LatLng point = new LatLng(location.getLatitude(), location.getLongitude());
			// fix: 一次性commit
			Preferences.saveLastSelfLocation(holder,
					new String[] { String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()) });
			Preferences.saveLastCityCode(holder, location.getCityCode());
			Preferences.saveLocationInfo(holder, location.getAddrStr());

			// Editor editor = Preferences.getPreferences(getActivity()).edit();
			// editor.putString(Preferences.SELF_POSITION,
			// String.valueOf(location.getLatitude())+ "#" +
			// String.valueOf(location.getLongitude()));
			// editor.putString(Preferences.SELF_CITY_CODE,
			// location.getCityCode());
			// editor.putString(Preferences.SELF_LOCATION_INFO,
			// location.getAddrStr());
			// editor.commit();

			drawSelfInfoOnTheMap(point);
		}
	};
	// PopupWindow mPopDeviceList;

	Dialog deviceListDialog;

	/**
	 * 显示设备列表对话框
	 */
	private void showDeviceListDialog() {
		// 加载设备列表视图
		View content = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_device_list, null);

		ListView listView = (ListView) content.findViewById(R.id.listview);
		// 填充设备列表数据
		listView.setAdapter(new DeviceListAdapter());

		// 设置对话框参数并且显示
		content.findViewById(R.id.layout_btn).setVisibility(View.GONE);
		deviceListDialog = new Dialog(holder, R.style.Theme_Light_NoTitle_NoShadow_Dialog);
		deviceListDialog.setContentView(content);
		deviceListDialog.setCanceledOnTouchOutside(true);
		deviceListDialog.setCancelable(true);
		deviceListDialog.show();
	}

	/**
	 * 设备列表对话框中设备列表适配器
	 */
	class DeviceListAdapter extends BaseAdapter {
		@Override
		public int getCount() {
			return DBLApplication.getInstance().deviceInfoList == null ? 0 : DBLApplication.getInstance().deviceInfoList.size();
		}

		@Override
		public Object getItem(int arg0) {
			return DBLApplication.getInstance().deviceInfoList == null ? null : DBLApplication.getInstance().deviceInfoList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int position, View view, ViewGroup arg2) {
			if (view == null) {
				view = LayoutInflater.from(getActivity()).inflate(R.layout.listitem_device_info, null);
			}
			if (DBLApplication.getInstance().deviceInfoList != null) {
				final DeviceInfo device = DBLApplication.getInstance().deviceInfoList.get(position);
				((TextView) view).setText(device.name);
				view.setTag(position);
				view.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// 设置点击设备为当前默认设备
						if (DBLApplication.getInstance().deviceInfoList != null) {
							DBLApplication.getInstance().currentDi = DBLApplication.getInstance().deviceInfoList.get((Integer) v.getTag());
						}
						deviceListDialog.dismiss();
						// 重新设置当前默认设备定位模式
						resetDeviceModeView();
						// 将当前设备信息画在地图上
						if (DBLApplication.getInstance().currentDi != null) {
							drawDeviceInfoOnTheMap(DBLApplication.getInstance().currentDi);
						}
					}
				});
			}
			return view;
		}
	}

	// 请求所有设备即时信息
	private void requestAllDeviceInfo() {
		if (!isHidden) {
			setAndShowWaitingMessage(R.string.wating_get_device_list);
		}
		((MainActivity) holder).getAllDeviceInfo(false);
	}

	@Override
	public void onResume() {
		super.onResume();
		mMapView.onResume();
		// 提示下载地图显示
		if (Preferences.shouldRemindDownMap(holder)) {
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					try {
						remindToDownMap();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}, 4000);
		}

		if (DBLApplication.getInstance().currentDi != null) {
			resetDeviceModeView();
		}

	}

	@Override
	public void onPause() {
		super.onPause();
		mMapView.onPause();
	}

	@Override
	public void onStop() {
		super.onStop();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		mMapView.onDestroy();
		
		unregisterPushReceiver();
		
	}

	/**
	 * 重新显示当前设备的当前定位模式
	 */
	private void resetDeviceModeView() {
		int currentMode = DBLApplication.getInstance().currentDi.location_mode;

		if (currentMode > lMode.length || currentMode < 1)
			currentMode = 1;
		txMode.setText(lMode[currentMode - 1]);
		if (currentMode == 1) {
			imgMode.setImageResource(R.drawable.mode_shengdian);
		} else if (currentMode == 2) {
			imgMode.setImageResource(R.drawable.mode_biaozhun);
		} else {
			imgMode.setImageResource(R.drawable.mode_zhuizong);
		}
		if (layoutMode.getVisibility() != View.VISIBLE) {
			layoutMode.setVisibility(View.VISIBLE);
			layoutMode.startAnimation(slideInRight);
		}
	}

	/** 提示去下载地图 */
	private void remindToDownMap() {
		if (holder == null) // fix
			return;
		// 检查网络环境
		int netState = NetworkUtils.getNetworkState(holder);
		if (NetworkUtils.MOBILE == netState || NetworkUtils.NONE == netState) {
			// 非Wi-Fi 提示方式
			showToast(R.string.map_down_tips);
			if (layoutMapDown.getVisibility() == View.VISIBLE) {
				layoutMapDown.startAnimation(AnimationUtils.loadAnimation(holder, R.anim.fade_out));
				layoutMapDown.setVisibility(View.GONE);
			}
		} else if (NetworkUtils.WIFI == netState) {
			// Wi-Fi 提示方式
			if (layoutMapDown.getVisibility() != View.VISIBLE) {
				layoutMapDown.setVisibility(View.VISIBLE);
				layoutMapDown.startAnimation(AnimationUtils.loadAnimation(holder, R.anim.slide_in_left));
			}
		}
	}

	/**
	 * 显示去下载地图对话框
	 */
	private void showToDownMapDialog() {
		final Dialog dialog = new Dialog(holder, R.style.Theme_Light_NoTitle_Dialog);
		View content = LayoutInflater.from(holder).inflate(R.layout.dialog_to_down_map, null);
		// final CheckBox ckNoRemind = (CheckBox)
		// content.findViewById(R.id.ck_no_remind);

		OnClickListener listener = new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// Preferences.saveShouldRemindDownMap(holder,
				// ckNoRemind.isChecked());
				// if (ckNoRemind.isChecked()) {
				// layoutMapDown
				// .startAnimation(fadeOut);
				// layoutMapDown.setVisibility(View.GONE);
				// }
				dialog.dismiss();

				if (arg0.getId() == R.id.btn_confirm) {
					OfflineMapDownActivity.launch(holder);
				}
			}
		};

		content.findViewById(R.id.btn_confirm).setOnClickListener(listener);
		content.findViewById(R.id.btn_cancel).setOnClickListener(listener);

		dialog.setCancelable(true);
		dialog.setCanceledOnTouchOutside(true);
		dialog.setContentView(content);
		dialog.show();
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if (!hidden && holder != null) {
			MainActivity main = (MainActivity) holder;
			main.showWaitingMessage();
			
			main.toAutoRereshList();
			DBLDebug.logd("location fragment show! main to auto Reresh data");
		}
	}

	OnClickListener toAddDeviceListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			DeviceAddTipActivity.launch(holder);
		}
	};

	private Dialog modiModeDialog;
	int currentMode;

	/**
	 * 显示修改设备模式对话框
	 */
	private void showModiLocationModeDialog() {
		View content = LayoutInflater.from(holder).inflate(R.layout.dialog_device_location_mode_2, null);
		content.findViewById(R.id.tx_mode_1).setOnClickListener(onModeChangeListener);
		content.findViewById(R.id.tx_mode_2).setOnClickListener(onModeChangeListener);
		content.findViewById(R.id.tx_mode_3).setOnClickListener(onModeChangeListener);

		modiModeDialog = new Dialog(holder, R.style.Theme_Light_NoTitle_NoShadow_Dialog);

		modiModeDialog.setContentView(content);
		modiModeDialog.setCanceledOnTouchOutside(true);
		modiModeDialog.setCancelable(true);
		modiModeDialog.show();
	}

	OnClickListener onModeChangeListener = new OnClickListener() {
		@Override
		public void onClick(View view) {

			switch (view.getId()) {
			case R.id.tx_mode_1:
				currentMode = 1;
				break;
			case R.id.tx_mode_2:
				currentMode = 2;
				break;
			case R.id.tx_mode_3:
				currentMode = 3;
				break;
			}
			dismissUpdateModeDialog();
			toModiLocationMode(currentMode);
		}
	};

	/**
	 * 发起修改请求
	 * 
	 * @param mode
	 *            修改的模式
	 */
	private void toModiLocationMode(final int mode) {
		if (!isHidden) {
			setAndShowWaitingMessage(R.string.wating_update);
		}

		final String mdn = DBLApplication.getInstance().currentDi.mdn;

		ServerApiFactory.getApiImpl().deviceModi(loginSign, mdn, null, null, mode, null, new RequestCallback() {
			@Override
			public void onSuccess(String rawData, Object response) {
				clearAndHiddenWaitingMessage();
				BaseResponse r = (BaseResponse) response;
				showToast(r.getDesc());
				// 成功！更新本地修改设备的模式
				if (r.getStatus().equals(Constants.REQUEST_SUCCESS)) {
					for (DeviceInfo d : DBLApplication.getInstance().deviceInfoList) {
						if (d.mdn.equals(mdn)) {
							d.location_mode = currentMode;
							break;
						}
					}
					// 刷新界面
					resetDeviceModeView();
				}
			}

			@Override
			public void onError(int statusCode, Throwable e, String rawData) {
				clearAndHiddenWaitingMessage();
				if (NetworkUtils.isNetConnect(holder)) {
					showToast(R.string.oper_error);
				} else {
					showToast(R.string.net_error);
				}
			}
		});
	}

	public void dismissUpdateModeDialog() {
		if (modiModeDialog != null && modiModeDialog.isShowing())
			modiModeDialog.dismiss();
		modiModeDialog = null;
	}

	/**
	 * 从本地加载设备头像
	 * 
	 * @param deviceImg
	 *            被头像填充的视图控件
	 */
	private void setDeviceHeadImg(final ImageView deviceImg) {
		try {
			if (DBLApplication.getInstance().currentDi == null || holder == null) {
				return;
			}
			final String imgid = DBLApplication.getInstance().currentDi.imei;
			// String imgName = Preferences.getDeviceImgName(holder, imgid);
			String localBase64 = Preferences.getDeviceImgBase64(holder, imgid);
			Bitmap localBitmap = null;
			if ("".equals(localBase64)) {
				Bitmap defaultImg = ImageUtils.toRoundBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.default_device_head));
				deviceImg.setImageBitmap(defaultImg);

				requestHead(deviceImg);
				DBLDebug.logd("location Fragment requestHead:" + deviceImg);
			} else {
				DBLDebug.logd("location Fragment set head from Preferences");
				localBitmap = ImageUtils.base64ToBitmap(localBase64.replaceAll(getResources().getString(R.string.add_mark), "+"));
				deviceImg.setImageBitmap(ImageUtils.toRoundBitmap(localBitmap));
				deviceImg.postInvalidate();
			}
		} catch (Exception e) {
			DBLDebug.loge("set device head img error\n" + e.getMessage());
		}
	}

	/**
	 * 从网络访问设备头像
	 * 
	 * @param deviceImg
	 *            被头像填充的视图控件
	 */
	private void requestHead(final ImageView deviceImg) {
		final String imgid = DBLApplication.getInstance().currentDi.imei;
		ServerApiFactory.getApiImpl().getImg(loginSign, imgid, new RequestCallback() {

			@Override
			public void onSuccess(String rawData, Object response) {
				GetImgResponse getImgResponse = (GetImgResponse) response;
				String base64 = "";

				if (getImgResponse.getStatus().equals(Constants.REQUEST_SUCCESS)) {
					if (null != getImgResponse.getImgdata() && !"".equals(getImgResponse.getImgdata())) {
						Preferences.saveDeviceImg(holder, getImgResponse.getImgdata(), imgid);
						// Preferences.saveDeviceImgName(holder,
						// getImgResponse.getImgname(), imgid);
						base64 = getImgResponse.getImgdata();

						Bitmap bm = null;
						try {
							bm = ImageUtils.base64ToBitmap(base64.replaceAll(getResources().getString(R.string.add_mark), "+"));
						} catch (Exception e) {
						}
						if (null != bm) {
							deviceImg.setImageBitmap(ImageUtils.toRoundBitmap(bm));
						}
					}
				}
			}

			@Override
			public void onError(int statusCode, Throwable e, String rawData) {
			}
		});
	}
	
	
	
	
	// ** push 推送 ** //
	private void registerPushReceiver(){
		if(holder != null) {
			IntentFilter intentFilter = new IntentFilter();
			intentFilter.addAction("com.igexin.sdk.action.QIZ0qPUiR1AS5PIZbNe2M2");
			holder.registerReceiver(pushReceiver, intentFilter);	
		} else {
			DBLDebug.loge("location fragment reg push fail,  activity null");
		}
	}
	
	private void unregisterPushReceiver(){
		if(holder != null) {
			holder.unregisterReceiver(pushReceiver);
		} else {
			DBLDebug.loge("location fragment unreg push fail,  activity null");
		}
	}
	
	private BroadcastReceiver pushReceiver = new BroadcastReceiver(){
		@Override public void onReceive(Context context, Intent intent) {
			Bundle bundle = intent.getExtras();
			switch (bundle.getInt(PushConsts.CMD_ACTION)) {
            case PushConsts.GET_MSG_DATA:
                byte[] payload = bundle.getByteArray("payload");
                if (payload != null) {
                    String data = new String(payload);
                    DBLDebug.logd("PushReceiver Got Payload:" + data);
                    if(!TextUtils.isEmpty(data)){
                    	if(data.startsWith(Constants.PUSH_MESSAGE_DEVICE_POSI)
                    			|| data.startsWith(Constants.PUSH_MESSAGE_DEVICE_NOPOSI)){
                    		if(viewTips != null){
                    			viewTips.stopAnim();
                    		}
                    		boolean success = data.startsWith(Constants.PUSH_MESSAGE_DEVICE_POSI);
                    		showToast(success ? R.string.wating_position_success : R.string.wating_position_fail);
                        }
                    }
                    
                    DBLDebug.logd("location fragment pushReceiver Payload:" + data);
                }
                break;
			}
		}
	};
	
}
